﻿using Sidvall.Collections;
using Sidvall.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Data;

namespace Sidvall.UI.Wpf.Converters
{
    public class ItemListValueConverter : IMultiValueConverter
    {
        #region Public Members

        #region Convert

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Sidvall.Data.IItem item;
            string propertyName, separator;

            var items = values[1] as IEnumerable<Sidvall.Data.IItem>;
            if (items == null)
                return null;
            var parameterItems = parameter.ToString(string.Empty).Split("|");
            if (parameterItems.Length > 0)
                propertyName = parameterItems[0];
            else
                propertyName = null;
            var valueItems = values[0] as System.Collections.IEnumerable;
            if ((valueItems == null) || (!valueItems.Any()))
            {
                var value = values[0].ToString(string.Empty);
                item = (from o in items
                        where o.Id == value
                        select o).FirstOrDefault();
                if (item == null)
                    return null;
                if (!string.IsNullOrWhiteSpace(propertyName))
                    return Sidvall.SystemContext.Current.CodeManager.GetPropertyValue(item, propertyName);
                return item.Name;
            }
            else
            {
                if (parameterItems.Length > 1)
                    separator = parameterItems[1];
                else
                    separator = ", ";
                var itemIndex = items.ToDictionary(o => o.Id, true, true);
                var names = new List<string>();
                foreach (var valueItem in valueItems)
                {
                    var key = Sidvall.SystemContext.Current.CodeManager.GetPropertyValue(valueItem, propertyName);
                    if (itemIndex.TryGetValue(key.ToString(string.Empty), out item))
                        names.Add(item.Name);
                }
                return (from o in names
                        orderby o
                        select o).JoinToString(separator);
            }
        }

        #endregion
        #region ConvertBack

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        #endregion

        #endregion
    }
}
